<template>
  <div class="L-form-container">
    <div v-for="(item,index) in jsondata.head" :key="index" style="margin-bottom:30px">
      <van-cell-group inset>
        <div class="L-form-title-row" @click="item.expand=!item.expand">
          <div>
            <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
            <span class="L-text L-primary-text-color">{{item.grouptitle}}</span>
          </div>
          <i class="iconfont" :class="item.expand ? 'icon-zhankai1' :'icon-xiayibu2'"></i>
        </div>
        <template v-if="item.expand">
          <div v-for="(fitem,findex) in item.groupvalue" :key="findex">
            <FormInput :formItem="fitem" @handleChange="handleChange"></FormInput>
          </div>
        </template>
      </van-cell-group>
    </div>
  </div>

  <van-cell-group inset>
    <div class="L-form-title-row">
      <div>
        <i class="iconfont icon-yuanzhu" style="color:#1683f7"></i>
        <span class="L-text L-primary-text-color">客户信息</span>
        <span style="color:red">*</span>
      </div>

      <span class="L-schedule-btn" @click="showeRefPopup = true">添加</span>
    </div>

    <van-row :gutter="10" v-for="(item,index) in customerArr" :key="index" class="L-customer-row">
      <van-col :span="21" class="L-small-text">
        {{item.sname}}
      </van-col>
      <van-col :span="3" style="text-align: center;">
        <i class="iconfont icon-xialingyingicon-39" style="color:#f66c6c;" @click="handleDeleteCustomer(index)"></i>
      </van-col>
    </van-row>
  </van-cell-group>

  <!-- 骨架屏 -->
  <div v-if="isLoading">
    <van-skeleton title :row="3" v-for="item in 5" :key="item" style="margin-bottom:30px" />
  </div>

  <div class="L-bottom-space"></div>
  <van-sticky position="bottom">
    <div class="L-bottom-row">
      <van-button round type="default" style="width:40%" @click="router.go(-1)">取消</van-button>
      <van-button round type="primary" style="width:40%" @click="handleSubmit">提交</van-button>
    </div>
  </van-sticky>

  <!-- 参照弹窗 -->
  <van-popup v-model:show="showeRefPopup" position="bottom" style="width:100%;height:100%">
    <template v-if="showeRefPopup">
      <Ref :refParams="refParams" :refObject="route.query.scenarioSelectobj" refMode="multi" :handleRefClick="handleRefClick" :handleRefCancle="handleRefCancle"></Ref>
    </template>
  </van-popup>

</template>

<script setup lang="ts">
import { ref, defineProps, onMounted, reactive, watch, computed } from "vue";
import {
  closeToast,
  showLoadingToast,
  showToast,
  showSuccessToast,
} from "vant";
import { useRoute, useRouter } from "vue-router";
const route = useRoute();
const router = useRouter();
import FormInput from "@/components/base/Form/FormInput.vue";
import Ref from "@/components/base/Ref/Ref.vue";

import { apiConfigurable } from "@/request/api/api";
import emitter from "@/utils/emitter";

//字段联动hooks
import { useFieldLinkage } from "@/hooks/hooks.js";
const { controlLinkArr, getFieldLink, handleFiledLink, flLogicalJudgment } =
  useFieldLinkage();

const scenarioId = route.query.scenarioId || "";
const scenarioTitle = route.query.scenarioTitle || "";

const showeRefPopup = ref(false);

const refParams = reactive({
  object: "",
  toobject: "",
  field: "idaccount",
  // id: props.formItem.sRefKey,
}
);

interface customerItem {
  id: any;
  sname: any;
  saddress: string;
}
const customerArr = ref<customerItem[]>([]);

function handleRefClick(refObj) {
  const { scenarioAccountobj } = route.query;
  const idArr = refObj.id.split(";").filter((item) => item);
  let titleArr = "";
  if (scenarioAccountobj === "contact") {
    const idaccount_ref_arr = refObj.idaccount_ref
      .split(";")
      .filter((item) => item);
    titleArr = refObj.title
      .split(";")
      .filter((item) => item)
      .map((item, index) => {
        return `${item} ${idaccount_ref_arr[index]}`;
      });
  } else {
    titleArr = refObj.title.split(";").filter((item) => item);
  }

  const addressArr = refObj.address.split(";").filter((item) => item);
  for (let i = 0; i < idArr.length; i++) {
    const item = { id: idArr[i], sname: titleArr[i], saddress: addressArr[i] };
    if (customerArr.value.every((citem) => citem.id !== item.id)) {
      customerArr.value.push(item);
    }
  }
  showeRefPopup.value = false;
}

function handleRefCancle() {
  showeRefPopup.value = false;
}

function handleDeleteCustomer(index: number) {
  customerArr.value.splice(index, 1);
}

import { useRouterStore } from "@/stores/router";
const routerStore = useRouterStore();

interface loadParams {
  [x: string]: any; //动态添加属性
}

const loadapi = ref("");
const loadParams: loadParams = {};

const submitapi = ref("");
const idobject = route.query.idobject;
if (route.query.itemid) {
  loadParams[`${idobject}_id`] = route.query.itemid;
}
loadapi.value = route.query.itemid
  ? `${idobject}.edit.do`
  : `${idobject}.new.do`;
submitapi.value = route.query.itemid
  ? `${idobject}.editsave.do`
  : `${idobject}.newsave.do`;

const isLoading = ref(false);

const idtemplate = route.query.idtemplate || "";

import type {jsondataVO} from "@/interface/interface"
let jsondata = ref<jsondataVO>({});
let orginData = ref({});

const pqzValue = ref({});

onMounted(() => {
  getData();
});

function getData() {
  isLoading.value = true;
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(loadapi.value, loadParams, "post").then((res) => {
    isLoading.value = false;
    res.data.jsondata.head = res.data.jsondata.head.map((item) => {
      item.expand = true;
      return item;
    });
    jsondata.value = res.data.jsondata;

    customerArr.value = res.data.mxList || [];
    closeToast();
    for (let indexName in jsondata.value.body) {
      for (let i = 0; i < jsondata.value.body[indexName].length; i++) {
        let item = jsondata.value.bodydata[indexName][i];
        for (let itemindex in item) {
          let itemdata = item[itemindex];
          if (itemdata.sField === "idaccount") {
            refParams.object = itemdata.idJoinObject
            refParams.toobject = itemdata.idObject
            return;
          }
        }
      }
    }

    //字段联动
    orginData.value = JSON.parse(JSON.stringify(res.data.jsondata));
    controlLinkArr.value = getFieldLink(jsondata.value);

    closeToast();
  });
}

const showePqzPopup = ref(false);
const schedulingType = ref("");
const schedulingArr = ref<{ lable: string; selected: boolean }[]>([]);

const pqzArr = computed(() => {
  return schedulingArr.value.filter((item) => {
    return item.selected;
  });
});

function saveDetailAccount() {
  for (let indexName in jsondata.value.body) {
    for (let i = 0; i < jsondata.value.body[indexName].length; i++) {
      let item = jsondata.value.bodydata[indexName][i];
      for (let itemindex in item) {
        let itemdata = item[itemindex];
        if (itemdata.sField === "idaccount") {
          this.detailAccount = itemdata;
          return;
        }
      }
    }
  }
}

// 字段值发生变化
function handleChange(item, value, valuehidden = "") {
  item.value = value;
  if (valuehidden) {
    item.valuehidden = valuehidden;
  }

  //字段联动
  handleFiledLink(item, jsondata.value, orginData.value);
}

interface submitData {
  [name: string]: any;
}
// 提交
function handleSubmit() {
  const data: submitData = {};
  const { idobject } = route.query;

  data[idobject + "_id"] =
    jsondata.value[idobject + "_id"] || route.query.itemid;

  data[idobject + "_idtemplate"] = idtemplate;
  for (let groupindex in jsondata.value.head) {
    let itemgroup = jsondata.value.head[groupindex].groupvalue;
    for (let itemindex in itemgroup) {
      let itemdata = itemgroup[itemindex];

      if (itemdata.lCanOutput === "0") {
        continue;
      }

      if (!checkForm(itemdata)) {
        return;
      }

      if (itemdata.sUIType === "ref") {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_ref"] =
          itemdata.value;
      } else if (itemdata.sUIType === "enum") {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_enum"] =
          itemdata.value;
      } else if (
        itemdata.sUIType === "file" ||
        itemdata.sUIType === "picture"
      ) {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.valuehidden;
        data[itemdata.idObject + "_" + itemdata.sField + "_title"] =
          itemdata.value;
      } else {
        data[itemdata.idObject + "_" + itemdata.sField] = itemdata.value;
      }
    }
  }
  // 对应客户数据
  data["khs"] = customerArr.value.length;
  data["extrainfo"] = customerArr.value.reduce((pre, item) => {
    return pre + item.sname + ";";
  }, "");
  data["customerids"] = customerArr.value.reduce((pre, item) => {
    return pre + item.id + ";";
  }, "");
  data["customeraddr"] = customerArr.value.reduce((pre, item) => {
    return pre + item.saddress + ";";
  }, "");
  data[idobject + "_jhcj"] = scenarioId;
  data[idobject + "_jhcj_ref"] = scenarioTitle;
  data[idobject + "_pqz"] = pqzArr.value.reduce((pre, item) => {
    return pre + item.lable + ";";
  }, "");

  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
    duration: 0,
  });

  apiConfigurable(submitapi.value, data, "post").then((res) => {
    if (res.code === 0) {
      showSuccessToast("提交成功!");
      closeToast();
      handleSubmited();
    }
  });
}

function handleSubmited() {
  routerStore.mode = "reload";
  router.go(-1);
}

function checkForm(itemdata) {
  if (
    itemdata.lMustInput === "1" &&
    itemdata.value === "" &&
    itemdata.lCanOutput === "1"
  ) {
    showToast(`${itemdata.sTitle}不能为空`);
    return false;
  }

  if (customerArr.value.length === 0) {
    showToast(`请选择对应客户`);
    return false;
  }

  return true;
}

function handlePqzConfirm() {}
</script>

<style scoped>
.L-date-tag {
  max-width: 70px;
  min-width: 40px;

  text-align: center;
  padding: 2px 5px;
  background: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 12px;
  margin: 0px 5px 10px;
}

.L-date-tag-selected {
  background: #1989fa;
  color: #fff;
}

.L-customer-row {
  width: 90%;
  margin: 10px auto;
  background: #fafafa;
  padding: 10px;
  border-radius: 6px;
}
</style>